package org.example.clouddemo.order.controller.admin;


import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.clouddemo.bean.common.entity.Order;
import org.example.clouddemo.order.OrderStatus;
import org.example.clouddemo.order.service.common.OrderService;
import org.example.clouddemo.order.service.common.param.CreateOrderParam;
import org.example.clouddemo.order.service.common.param.DeleteOrderParam;
import org.example.common.annotation.IgnoreAuth;
import org.example.common.auth.TokenService;
import org.example.common.bean.LoginUser;
import org.example.common.response.ApiResult;
import org.example.common.utils.SecurityUtils;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.server.PathParam;
import java.util.List;

/**
 * 订单服务Controller
 */
//@CrossOrigin
@Slf4j // 日志注解
@RefreshScope //自动刷新配置内容
@Api(tags = "订单app接口")
@ApiSupport(order = 1)
@RequiredArgsConstructor
@RestController("adminOrderController")
@RequestMapping("/api/admin/order")
public class OrderController {

    private final TokenService tokenService;

    private final OrderService orderService;

    /**
     * 订单创建
     * 需要token
     * @param param 请求体是CreateOrderParam对象的JSON数据（字段应当与CreateOrderParam类相匹配）
     * @return 带订单id返回 或者 失败原因
     */
    @ApiOperation(value = "创建订单", notes = "返回结果是订单id")
    @PostMapping({"create"})
    public ApiResult<String> createOrder(@RequestBody CreateOrderParam param) {
        //获取当前用户
        Long userId = SecurityUtils.getUserId();
        // 解析参数
        Order order = new Order();
        order.setProductId(param.getProductId());
        order.setUserId(userId);
        order.setQuantity(param.getQuantity());

        String result=orderService.createOrder(order);
        //判断 result是否含有id
        if(result.contains(OrderStatus.ORDER_SUCCESS.getDesc()))
            return ApiResult.success(result.substring(OrderStatus.ORDER_SUCCESS.getDesc().length()));
        else
            return ApiResult.error(result);
    }

    /**
     * 订单删除
     * @param param 删除订单参数
     * @return 返回执行结果
     */
    //需要token
    @DeleteMapping({"delete"})
    @IgnoreAuth
    public ApiResult<Integer> deleteOrder(@RequestBody DeleteOrderParam param) {
        //获取当前用户
        LoginUser loginUser = SecurityUtils.getUserInfo();
        log.info("当前的用户类别：{}", loginUser.getUserType()); // 用于用户对象判断
        // 执行删除并返回执行结果
        return ApiResult.success(orderService.deleteByOrderId(param.getOrderId(),loginUser));
    }

    /**
     * 查询全部订单
     * @return 查询结果
     */
    @GetMapping("queryAll")
    @IgnoreAuth
    public ApiResult<List<Order>> selectAllOrders() {
        if(!isAdmin()) return ApiResult.error(OrderStatus.NO_ADMIN_ROLE.getDesc());
        List<Order> orders=orderService.queryOrdersByAll();
        if(orders==null){return ApiResult.error(OrderStatus.RESULT_EMPTY.getDesc());}
        return  ApiResult.success(orders);
    }
    /**
     * 判断当前用户是否是管理员
     * @return
     */
    public boolean isAdmin(){
        //获取当前用户
        LoginUser loginUser = SecurityUtils.getUserInfo();
        log.info("当前的用户类别：{}", loginUser.getUserType()); // 用于用户对象判断
        if(loginUser.getUserType().equals("admin")){
            return true;
        }
        return false;
    }
    /***
     * 根据用户ID查询订单
     * @param userId
     * @return
     */
    @GetMapping({"queryByUserId/{userId}"})
    @IgnoreAuth
    public ApiResult <List<Order>>  getByUserId(@PathVariable Long userId) {
        if(!isAdmin()) return ApiResult.error(OrderStatus.NO_ADMIN_ROLE.getDesc());
        if(userId==null){return ApiResult.error();}
        List<Order> orders=orderService.getOrdersByUserId(userId);
        if(orders==null){return ApiResult.error();}
        return ApiResult.success(orders);
    }


}
